#include "gameplaylayer.h"

#include "../graphic/scene/scenegraph.h"
#include "../graphic/scene/nodemodel.h"
#include "../graphic/scene/nodecamera.h"
#include "../graphic/scene/nodeinput.h"
#include "resources/resourcerendertarget.h"
#include "resources/resourceeffect.h"
#include "resources/resourcemodel.h"
#include "../graphic/scene/noderoot.h"



namespace gunsmith
{
CGameplayLayer::CGameplayLayer()
{
	m_pSceneGraph = NULL;
	Init();
}

CGameplayLayer::~CGameplayLayer()
{
	if(m_pSceneGraph)
	{
		m_pSceneGraph->DestroyTree();
		delete m_pSceneGraph;
	}
}

void CGameplayLayer::Init()
{
	m_pNodeRoot = new CNodeRoot();
	m_pSceneGraph = new CSceneGraph(m_pNodeRoot);

	CNodeInput *pInputNode = new CNodeInput();
	m_pNodeRoot->AddChild(pInputNode);

	// create model resources
	CResourceModel* pResModel = m_pResMngr->CreateResource<CResourceModel>("model_tiny", "media/tiny.x");
	CResourceEffect* pResEffect = m_pResMngr->CreateResource<CResourceEffect>("effect_bonetransformation", "media/bonetransformation.fx");

	m_pRTTexCoords	= m_pResMngr->CreateResource<CResourceRenderTarget>(RID_RENDERTARGET_TEXCOORDS);
	m_pRTNormals	= m_pResMngr->CreateResource<CResourceRenderTarget>(RID_RENDERTARGET_NORMALS);
	m_pEffectComb	= m_pResMngr->CreateResource<CResourceEffect>("effect_combined", "media/combined.fx");

	m_pModel = new CNodeModel(pResModel, pResEffect); 
	m_pModel->SetDirection(D3DXVECTOR3(0,0,1000));
	m_pNodeRoot->AddSibbling(m_pModel);

	// create camera
	m_pCamera = new CNodeCamera(D3DX_PI/4, 4.0f/3.0f, 1.0f, 3000.0f, m_pDevice);
	m_pCamera->SetPosition(D3DXVECTOR3(500, 0, 0));
	m_pCamera->FocusOn(m_pModel);	
	m_pNodeRoot->AddSibbling(m_pCamera);
	
	m_pSceneGraph->SetDebug(false);
}

void CGameplayLayer::RenderScene(float fDelta)
{
	static int iDecider = 1;
	static bool bSwitch = false;
	D3DXVECTOR3 vDirection(0,0,1000);
	float fLength = D3DXVec3Length(&m_pModel->GetPosition());
	
	if(fLength >= 1200 && !bSwitch)
	{
		iDecider *= -1;
		bSwitch = !bSwitch;
	}

	if(fLength <= 1000 && bSwitch)
		bSwitch = !bSwitch;
	
	m_pModel->SetDirection(m_pModel->GetDirection()+(vDirection*iDecider*fDelta));
	if(D3DXVec3Length(&m_pModel->GetDirection()) >= vDirection.z)
		m_pModel->SetDirection(vDirection*iDecider);
	
// ------------------------------------ actual part of the library ------------------------------------
	m_pSceneGraph->Update(fDelta);
	m_pSceneGraph->DrawTo("Texture_Info", m_pRTTexCoords);
	m_pSceneGraph->DrawTo("Normals", m_pRTNormals);
	m_pSceneGraph->DrawCombined(m_pEffectComb);
}
};